#author devdoer@gmail.com
#$Id: activeobject.py 24 2006-06-25 05:27:12Z devdoer $
'''
this class will do action(as you define)  in period in the back-ground thread
you subclass TimedActiveObject to define your own action
'''

import threading,time
class TimedActiveObject:
	MAX_TIME_LIMIT=600#s
	CHECK_PERIOD=30#s
	def __init__(self):
		self.__bAction=True
		self.__run_bg_thread()
	def __run_bg_thread(self):
		t=threading.Thread(target=self.__bg_thread)
                t.setDaemon(True)
                t.start()
	def __bg_thread(self):
		tick=0
                while True:
                        if tick>=self.MAX_TIME_LIMIT:
				print 'time limit...'
                                self.__bAction=True
                        if self.__bAction:
                                self._action()
                                self.__bAction=False
                                tick=0
                        time.sleep(self.CHECK_PERIOD)
                        tick+=self.CHECK_PERIOD
	def notify_action(self):
		#if  action is in execution ,then this notify will have no effect
		#or,if  action has been notified ,then  this notify will have no effect,ie. action will
		# executes once only	
		self.__bAction=True
	def _action(self):
		self._timed_action()
		
def test():
	class X(TimedActiveObject):
		MAX_TIME_LIMIT=60
		CHECK_PERIOD=10
		def __init__(self):
			self.i=0
			TimedActiveObject.__init__(self)
		def _action(self):
			print 'X::_action()'
		def f(self):
			self.i+=1	
			if self.i>3:
				self.notify_action()
	obj=X()
	obj.f()
	obj.f()
	obj.f()
	obj.f()
	time.sleep(1000)

if __name__=='__main__':
	test()
		
